#coding=utf-8

import hashlib
import time

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        """Return a new Block object. Each block is "chained" to its previous
        by calling its unique hash.

        Args:
            index (int): Block number.
            timestamp (int): Block creation timestamp.
            data (str): Data to be sent.
            previous_hash(str): String representing previous block unique hash.

        Attrib:
            index (int): Block number.
            timestamp (int): Block creation timestamp.
            data (str): Data to be sent.
            previous_hash(str): String representing previous block unique hash.
            hash(str): Current block unique hash.

        """
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.nonce = 1024
        self.hash = None


    def mine_block(self):
        sha = hashlib.sha256()
        nonce_temp = self.nonce
        while(True):
            nonce_temp = nonce_temp + 1
            sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash) + str(self.nonce)).encode('utf-8'))
            hash_temp = sha.hexdigest()
            print hash_temp
            if hash_temp.startswith('000'):
                break
            else:
                time.sleep(0.1)
        self.hash = hash_temp
        print("Block hash:{0}\n Nonce:{1}".format(self.hash, nonce_temp))
        self.nonce = nonce_temp